<script setup lang="ts">
import { reactive, ref, unref, watch, onMounted } from 'vue'
import { Form } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'

// , ElCheckbox, ElLink
import { ElButton } from 'element-plus'
import { required } from '@/utils/formRules'
import { useForm } from '@/hooks/web/useForm'
import { loginApi, getUserMenus, googleVerify } from '@/api/login'
import type { UserLoginType } from '@/api/login/types'
import { useCache } from '@/hooks/web/useCache'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { getMd5Password, getCurUser } from '@/utils'
import logo from '@/assets/imgs/logoB.png'
import hello from '@/assets/imgs/hello.png'
import { ElMessage } from 'element-plus'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import inputCode from './inputCode.vue'
import { useEmitt } from '@/hooks/web/useEmitt'
import { companyDetail } from '@/api/company'
const appStore = useAppStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()

const { t } = useI18n()
const localeStore = useLocaleStoreWithOut()
const { wsCache } = useCache()
const baseUrl = ref((import.meta.env.VITE_BASE_PATH as string) + 'logoLogin.png')
//当前语言

let apiRouters: AppCustomRouteRecordRaw[] = []
const rules = {
  userName: [required],
  password: [required]
}
const state = reactive({
  // 表格數據
  loginSuccess: {},
  test: '',
  QRBarcodeURL: null,
  isBind: -1,
  googleCode: null,
  num1: null,
  num2: null,
  num3: null,
  num4: null,
  num5: null,
  num6: null,
  loading: false
})
onMounted(async () => {
  document.onkeydown = function (e) {
    var key = window.event.keyCode
    if (key == 13) {
      console.log(e)
      //const { wsCache } = useCache()
      if (currentRoute.value.path != '/login') return
      if (state.isBind == 0 || state.isBind == 1) {
        if (state.isBind == 1) state.googleCode = wsCache.get('googleCode')
        console.log(state.googleCode)
        toGoogleBindLogin()
      }
    }
  }
})
const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    }
  },
  {
    field: 'userName',
    value: 'ez',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.usernamePlaceholder')
    }
  },
  {
    field: 'password',
    value: '123456',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%',
        marginTop: '15px'
      },
      placeholder: t('login.passwordPlaceholder'),
      clearable: false
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    }
  },
  {
    field: 'otherIcon',
    colProps: {
      span: 24
    }
  }
])

//const iconSize = 30

// const remember = ref(false)

const { register, elFormRef, methods } = useForm()

//const iconColor = '#999'

const redirect = ref<string>('')

const dialogVisible = ref(false)

// const isBind = ref(false)

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// 打開綁定
const openBind = () => {
  dialogVisible.value = false
  toBind()
}

// 登录
const signIn = async () => {
  dialogVisible.value = false
  const formRef = unref(elFormRef)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      state.loading = true
      const { getFormData } = methods
      const formData = await getFormData<UserLoginType>()
      var sendPassword = getMd5Password(formData.password)
      formData.userName = formData.userName.replace(/\s/g, '')
      console.log('loginApi==========')
      const res = await loginApi({
        userName: formData.userName,
        password: sendPassword
      })
        .catch(() => {})
        .finally(() => (state.loading = false))
      const result = res as any
      if (result && result.success) {
        console.log('checkres', res)
        state.loginSuccess = res
        state.QRBarcodeURL = res.data.QRBarcodeURL
        let bind = res.data.isBind
        if (state.QRBarcodeURL == undefined) {
          login()
        } else {
          if (bind == 1) {
            toBind()
          } else dialogVisible.value = true
        }
      }
    }
  })
}

const toBind = () => {
  state.isBind = state.loginSuccess.data.isBind
}
const login = () => {
  const { wsCache } = useCache()
  wsCache.set(appStore.getUserInfo, state.loginSuccess)
  getCompanyDetail()
  getMenus()
}

// keyDownBindLogin
//谷歌验证码绑定认证
const toGoogleBindLogin = async () => {
  if (!state.googleCode) {
    ElMessage.error(t('login.key'))
    return
  }
  const { getFormData } = methods
  const formData = await getFormData<UserLoginType>()
  var sendPassword = getMd5Password(formData.password)
  let params = {
    userName: formData.userName,
    password: sendPassword,
    googleCode: state.googleCode
  }
  await googleVerify(params).then((res) => {
    if (res) {
      login()
    }
  })
}
useEmitt({
  //绑定
  name: 'toBindLogin',
  callback: (msg) => {
    if (msg.length > 5) {
      state.googleCode = msg
    } else {
      ElMessage.error(t('login.key'))
      return
    }
    toGoogleBindLogin()
  }
})
useEmitt({
  //返回
  name: 'backPage',
  callback: () => {
    state.isBind = -1
  }
})
//获取公司信息
const getCompanyDetail = async () => {
  const user = getCurUser() as any
  const id = user.tenantId
  //公司資料
  if (!id) return
  const company = await companyDetail({ tenantId: id })
  wsCache.set('companyData', company)
}
// }
// 获取菜单信息
const getMenus = async () => {
  const res = await getUserMenus()
  //转换菜单为路由
  apiRouters = []
  convertMenus(res.data)
  const { wsCache } = useCache()
  const routers = apiRouters
  wsCache.set('groupRouters', routers)
  //参数为none由取路由页面定义的路由，admin则为后台菜单生成的路由
  await permissionStore.generateRoutes('admin', routers).catch(() => {})
  permissionStore.getAddRouters.forEach((route) => {
    addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
  })
  permissionStore.setIsAddRouters(true)
  push({ path: permissionStore.getRouters[0].path })
}
/**
 * @description 将后台接口返回的菜单转换成AppCustomRouteRecordRaw数组
 * @author Elwin ZHANG
 * @date 2022-05-30 11:29
 */
const convertMenus = (menus: []) => {
  if (!menus || menus.length == 0) {
    return
  }
  //构建一级路由
  for (const amenu of menus) {
    const dbMenu = amenu as any
    if (!dbMenu.pageLevel || dbMenu.pageLevel == 1) {
      let router = convertOneMenu(dbMenu)
      apiRouters.push(router)
    }
  }
  //构建子路由
  for (const router of apiRouters) {
    buildMenus(menus, router)
  }
}

/**
 * @description 构建子路由（递归）
 * @author Elwin ZHANG
 * @date 2022-05-30 15:08
 */
const buildMenus = (menus: [], router: AppCustomRouteRecordRaw) => {
  //循环查找当前中由的子路由
  const pid = router.meta.id
  for (const amenu of menus) {
    const dbMenu = amenu as any
    //没有父节点，则继续
    if (!dbMenu.parentId) {
      continue
    }
    //匹配到子节点
    if (pid == dbMenu.parentId) {
      let child = convertOneMenu(dbMenu)
      router.children?.push(child)
      //递归子节点
      buildMenus(menus, child)
    }
  }
}

/**
 * @description 转换数据库中的一条菜单记录为前端由路由对象，忽略子菜单
 * @author Elwin ZHANG
 * @date 2022-05-30 14:52
 */
const convertOneMenu = (menu: any): AppCustomRouteRecordRaw => {
  const dbMenu = menu as any
  const path = dbMenu.url as string
  //根据语言设置取不同的字段
  let title = dbMenu.menuName
  const curLang = localeStore.getCurrentLocale.lang

  if (curLang == 'en') {
    title = dbMenu.enName
  }
  //组件字段去掉前缀'/'以及后缀'.vue'
  let component = dbMenu.component as string
  if (component.startsWith('/')) {
    component = component.substring(1)
  }
  if (component.endsWith('.vue')) {
    component = component.replace('.vue', '')
  }
  let router: AppCustomRouteRecordRaw = {
    path: path,
    name: path.replace('/', ''),
    component: component,
    children: [],
    meta: {
      title: title,
      icon: dbMenu.icon,
      level: dbMenu.pageLevel,
      name: dbMenu.menuName,
      enName: dbMenu.enName,
      hkName: dbMenu.hkName,
      id: dbMenu.menuId,
      params: dbMenu.params,
      idName: 'menu_' + dbMenu.menuId, //用来定位设置教程
      noCache: true // 如果设置为true，则不会被 <keep-alive> 缓存(默认 false)
    },
    redirect: dbMenu.navUrl
  }
  if (dbMenu.hidden && dbMenu.hidden == 1) {
    router.meta.hidden = true
    router.meta.canTo = true
  }
  //外部链接类型处理
  if (dbMenu.menuType == 2) {
    router.component = '#'
    if (dbMenu.pageLevel != 1) {
      router.path = component
      router.meta.link = component
    } else {
      //一级菜单是外部链接的话还要特殊处理
      if (!router.path.startsWith('/')) {
        router.path = '/' + router.path
      }
      let child = { path: component, meta: { title: title, name: dbMenu.menuId, link: component } }
      router.children?.push(child)
    }
    console.log('链接路由：' + JSON.stringify(router))
  }
  return router
}
</script>
<template>
  <Form
    v-if="state.isBind == -1"
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    @register="register"
    @submit.prevent
  >
    <template #title>
      <!-- <h2 class="text-2xl font-bold text-center w-[100%]">{{ t('login.login') }}</h2> -->
      <div style="margin-left: auto; margin-right: auto; margin-bottom: 40px">
        <img :src="baseUrl" alt="" />
      </div>
    </template>

    <!-- <template #tool>
      <div class="mt-10px flex justify-between items-center w-[100%]">
        <ElCheckbox
          v-model="remember"
          :label="t('login.remember')"
          size="small"
          style="color: white"
        />
        <ElLink type="primary" :underline="false" style="font-size: 12px; color: white">{{
          t('login.forgetPassword')
        }}</ElLink>
      </div>
    </template> -->
    <template #login>
      <ElButton
        :loading="state.loading"
        v-btnAntiShake="signIn"
        type="primary"
        class="mt-50px w-[100%]"
        native-type="submit"
      >
        <!--  -->
        <!-- @click="signIn" -->
        <!-- @click="dialogVisible = true" -->
        {{ t('login.login') }}
      </ElButton>
    </template>
  </Form>
  <!-- //v-else-if="state.isBind == 0" -->
  <div class="google" v-show="state.isBind == 0">
    <div class="google-header">
      <!-- style="width: 20%" -->
      <el-image :src="logo" />
      <p style="display: block">{{ t('login.bind') }} Google Authentication</p>
      <el-input :placeholder="t('login.key')" v-model="state.googleCode" />
    </div>
    <div class="google-body">
      <div>
        <p>{{ t('login.first') }}: {{ t('login.scanDownload') }}</p>
        <el-image style="height: 120px; width: 120px" :src="hello" />
      </div>
      <div>
        <p>{{ t('login.second') }}: {{ t('login.scanBind') }}</p>
        <!-- <img crossorigin="anonymous" style="height: 120px; width: 120px" :src="state.QRBarcodeURL"
        /> -->
        <el-image style="height: 120px; width: 120px" :src="state.QRBarcodeURL" />
      </div>
    </div>
    <p class="google-mark">{{ t('login.remark') }}</p>
    <div class="google-footer">
      <el-row
        ><el-button type="primary" size="large" @click="toGoogleBindLogin">{{
          t('login.finish')
        }}</el-button></el-row
      >
      <el-row
        ><el-button size="large" @click="state.isBind = -1">{{
          t('login.back')
        }}</el-button></el-row
      >
    </div>
  </div>
  <div class="safe" v-show="state.isBind == 1">
    <div class="safe-header">
      <!-- style="width: 20%" -->
      <el-image :src="logo" />
      <p style="display: block">{{ t('login.safe') }} </p>
    </div>
    <p class="safe-mark">{{ t('login.code') }}</p>
    <div class="safe-body">
      <input-code />
    </div>
  </div>

  <!-- 綁定Google對話框 -->
  <div class="dialog">
    <el-dialog v-model="dialogVisible" width="30%" center draggable>
      <el-image :src="logo" style="width: 20%" />
      <span style="display: block">{{ t('login.isBind') }}</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button style="margin-right: 20px" type="primary" @click="openBind">{{
            t('login.bind')
          }}</el-button>
          <el-button style="margin-left: 20px" @click="login">{{ t('login.pass') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.el-card__header {
  border-bottom: none;
  box-sizing: border-box;
}
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
// 綁定Google對話框樣式
.dialog {
  :deep(.el-dialog) {
    border-radius: 7px !important;
    margin: 0 !important;
    position: absolute;
    top: 45%;
    left: 50%;
    transform: translate(-50%, -50%);
    .el-dialog__body {
      text-align: center;
      font-size: 15px;
      font-weight: 600;
    }
  }
}

// 綁定Google頁面樣式
.google {
  font-size: 13px;
  color: var(--el-text-color-regular);
  margin: 0 auto;
  font-weight: 700;
  .google-header {
    color: white;
    text-align: center;
    font-size: 20px;
    // color: #000;
    .el-input {
      padding: 20px 0;
      width: 430px;
    }
  }
  .google-body {
    color: white;
    width: 430px;
    padding: 0 35px;
    display: flex;
    justify-content: space-between;
    text-align: center;
    .el-image {
      width: 45%;
      margin-top: 5px;
    }
  }
  .google-mark {
    color: white;
    width: 430px;
    padding: 5px 20px;
    text-align: center;
    font-size: 12px;
    font-weight: normal;
  }
  .google-footer {
    width: 430px;
    margin-top: 10px;
    .el-row {
      width: 100%;
      margin-bottom: 20px;
    }
    .el-button {
      width: 100%;
    }
  }
}
// 安全验证頁面樣式
.safe {
  font-size: 13px;
  color: var(--el-text-color-regular);
  margin: 0 auto;
  font-weight: 700;
  .safe-header {
    text-align: center;
    font-size: 20px;
    color: #000;
    .el-input {
      padding: 20px 0;
      width: 430px;
    }
  }
  .safe-body {
    width: 430px;
    padding: 0 10px;
    display: flex;
    justify-content: space-between;
    text-align: center;
    align-items: center;
    justify-content: center;
  }
  .safe-mark {
    width: 430px;
    padding: 5px 20px;
    text-align: center;
    font-size: 12px;
    font-weight: normal;
  }
  .safe-footer {
    width: 430px;
    margin-top: 10px;

    .el-row {
      width: 100%;
      margin-bottom: 20px;
    }
    .el-button {
      width: 100%;
    }
  }
}

#phonePassword {
  position: relative;
  width: 500px;
  height: 120px;
  margin: auto;
}
#phonePassword input {
  width: 60px;
  height: 60px;
  border: 1px solid #000000;
  font-size: 50px;
  text-align: center;
}
#phonePassword .inputText {
  background-color: transparent;
  color: transparent;
  outline: none;
  width: 390px;
  position: absolute;
  top: 50px;
  z-index: 1;
  left: 0px;
}

// :deep(#phonePassword input::-webkit-outer-spin-button),
// :deep(#phonePassword input::-webkit-inner-spin-button) {
//   -webkit-appearance: none;
// }
// :deep(#phonePassword input[type='number']) {
//   -moz-appearance: textfield;
// }

// :deep #phonePassword input {
//   border: none;
// }

:deep(.el-input .el-input__wrapper) {
  height: 40px;
}
</style>
